(function () {
  let number = 2;
  const numberTxt = document.querySelector(".prize-number");
  const startbtn = document.querySelector(".handler-container-btn");
  const prizeLists = document.querySelectorAll(".prize-list");
  const dialog = document.querySelector(".dialog-container");
  const prizeContent = dialog.querySelector(".content");
  const cliseBtn = dialog.querySelector(".close");
  const againBtn = dialog.querySelector(".button");

  let index = -1;
  let currentIndex = null;
  let timerId = null;

  function init() {
    numberTxt.innerHTML = number;
    bindEvent();
  }

  function bindEvent() {
    startbtn.addEventListener("click", onStartBtnClick);
    cliseBtn.addEventListener("click", onCloseBtnClick);
    againBtn.addEventListener("click", onAgainBtnClick);
  }

  function onStartBtnClick() {
    if (!number) return;
    runGame();
  }

  function stop() {
    clearInterval(timerId);
    timerId = null;
    openDialog();
  }

  function openDialog() {
    dialog.style.display = "block";
    if (!number) {
      againBtn.innerHTML = "确定";
    }

    if (currentIndex !== 4) {
      prizeContent.innerHTML =
        "恭喜你获得" + prizeLists[currentIndex].querySelector("span").innerHTML;
    } else {
      prizeContent.innerHTML = "加油";
    }
  }

  function onCloseBtnClick() {
    dialog.style.display = "none";
  }

  function onAgainBtnClick() {
    dialog.style.display = "none";
    if (!number) return;
    runGame();
  }

  function runGame() {
    if (timerId) {
      return;
    }
    let num = 3000 + Math.floor(Math.random() * 6000);
    timerId = setInterval(() => {
      num -= 200;

      if (num <= 200) {
        stop();
        return;
      }

      currentIndex = ++index % prizeLists.length;
      prizeLists.forEach((node) => {
        node.classList.remove("active");
      });
      prizeLists[currentIndex].classList.add("active");
    }, 200);
    numberTxt.innerHTML = --number;
  }

  init();
})();
